#include "motorworker.h"
#include "qthread.h"
#include <QDateTime>

MotorWorker::MotorWorker(ushort di, ushort d0, int mode, QObject *parent)
    : SensorWorker(di, d0, parent), m_mode(mode) {}

void MotorWorker::stop()
{
    m_running = false;
}

void MotorWorker::process()
{
    clearInputEdge();

    while (m_running) {
        ushort rising_edge_count = 0;
        if (checkInputEdge(rising_edge_count)) {
            handleButtonPress();
            clearInputEdge();
        }
        QThread::msleep(10);
    }
    emit finished();
}

void MotorWorker::handleButtonPress()
{
    switch (m_mode) {
    case 0: // 启动
        setOutputBit(0);
        emit log("[" + QDateTime::currentDateTime().toString() +
                 "] Motor start signal triggered");
        emit motorStateChanged(true);
        break;
    case 1: // 停止
        setOutputBit(0xFFFF);
        emit log("[" + QDateTime::currentDateTime().toString() +
                 "] Motor stop signal triggered");
        emit motorStateChanged(false);
        break;
    case 2: // 急停
        MCF_Axis_Stop_Net(0, 0, 0);
        MCF_Set_Output_Net(0xFFFF, 0);
        emit log("[" + QDateTime::currentDateTime().toString() +
                 "] Emergency stop triggered");
        emit motorStateChanged(false);
        break;
    }
}
